import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/store/user';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

// NProgress配置
NProgress.configure({ showSpinner: false });

// 公共路由
const publicRoutes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录', hidden: true }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/login/404.vue'),
    meta: { title: '404', hidden: true }
  },
  {
    path: '/redirect',
    name: 'Redirect',
    meta: { hidden: true },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/layout/components/Redirect.vue'),
      }
    ]
  }
];

// 需要权限控制的路由
const protectedRoutes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '仪表盘', icon: 'Monitor' }
      },
      {
        path: '/systemManagement',
        name: 'SystemManagement',
        meta: { title: '系统管理', icon: 'User', alwaysShow: true },
        children: [
          {
            path: '/user-management',
            name: 'UserManagement',
            component: () => import('@/views/user-management/index.vue'),
            meta: { title: '用户管理', icon: 'UserFilled' }
          }
        ]
      },
      {
        path: '/Config',
        name: 'Config',
        meta: { title: '配置', icon: 'Setting' , alwaysShow: true},
        children: [
          {
            path: '/db-config',
            name: 'DBConfig',
            component: () => import('@/views/db-config/index.vue'),
            meta: { title: '数据库配置', icon: 'Setting' }
          }
        ]
      },
      {
        path: '/data-sync',
        name: 'DataSync',
        component: () => import('@/views/data-sync/index.vue'),
        redirect: '/data-sync/task',
        meta: { title: '数据同步', icon: 'Connection', alwaysShow: true },
        children: [
          {
            path: '/task',
            name: 'DataSyncTask',
            component: () => import('@/views/data-sync/task/index.vue'),
            meta: { title: '同步任务', icon: 'RefreshRight' }
          },
          {
            path: '/log',
            name: 'ExecutionLog',
            component: () => import('@/views/data-sync/execution-log/index.vue'),
            meta: { title: '执行日志', icon: 'Document' }
          }
        ]
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/profile/index.vue'),
        meta: { title: '个人中心', icon: 'Avatar', hidden: true }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    meta: { hidden: true }
  }
];

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: [...publicRoutes, ...protectedRoutes],
  // 平滑滚动
  scrollBehavior: () => ({ left: 0, top: 0 })
});

// 路由前置守卫
router.beforeEach((to, from, next) => {
  NProgress.start(); // 开始进度条
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - DBCompareX` : 'DBCompareX';
  
  const userStore = useUserStore();
  
  // 如果已登录，但访问登录页，则重定向到首页
  if (userStore.isLoggedIn() && to.path === '/login') {
    next({ path: '/' });
    NProgress.done();
  } 
  // 如果访问的非登录页，需要认证
  else if (to.path !== '/login' && !userStore.isLoggedIn()) {
    next({ path: '/login', query: { redirect: to.fullPath } });
    NProgress.done();
  }
  // 其他情况放行
  else {
    next();
  }
});

// 路由后置守卫
router.afterEach(() => {
  NProgress.done(); // 结束进度条
});

export default router;